package com.tpshion.util.tpsh.config;

import com.tpshion.util.tpsh.filter.ReplaceStreamFilter;
import com.tpshion.util.tpsh.interceptor.RequestLogInterceptor;
import com.tpshion.util.tpsh.properties.RequetLogProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;

/**
 * 请求日志自动配置类
 */
@Configuration
@ConditionalOnClass(WebMvcConfigurer.class)
@EnableConfigurationProperties(RequetLogProperties.class)
@ConditionalOnProperty(prefix = "tpsh.log", value = "enabled", matchIfMissing = true)
public class RequestLogAutoConfiguration implements WebMvcConfigurer{

    private static final Logger log = LoggerFactory.getLogger(RequestLogAutoConfiguration.class);

    private RequetLogProperties properties;

    public RequestLogAutoConfiguration(RequetLogProperties properties){
        log.info("init RequestLogAutoConfiguration...");
        this.properties = properties;
    }

    @Bean
    @ConditionalOnMissingBean
    public RequestLogInterceptor requestLogInterceptor(){
        return new RequestLogInterceptor();
    }

    @Bean
    @ConditionalOnMissingBean
    public ReplaceStreamFilter replaceStreamFilter(){
        return new ReplaceStreamFilter();
    }

    @Bean
    @ConditionalOnMissingBean
    public FilterRegistrationBean filterRegistrationBean(ReplaceStreamFilter replaceStreamFilter){
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(replaceStreamFilter);
        registration.addUrlPatterns(properties.getPath());
        registration.setName(properties.getFilterName());
        registration.setOrder(properties.getOrder());
        return registration;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(requestLogInterceptor()).order(properties.getOrder())
                .addPathPatterns(properties.getPath())
                .excludePathPatterns(StringUtils.hasLength(properties.getExclude()) ? Collections.emptyList() : Arrays.stream(properties.getExclude().split(",")).collect(Collectors.toList()));
        log.info("registry RequestLogInterceptor success");
    }

}
